import React, { PureComponent } from 'react';
import {
    StyleSheet, FlatList,
    Text,
    View, Button, Image,
    Animated, TouchableHighlight
} from 'react-native';
import DeviceRn from '../Tools/device';
import Http from '../Tools/http.unite';
import { connect } from 'react-redux';
import Toast, { DURATION } from 'react-native-easy-toast';
//导入action

let DevWH = DeviceRn().getWidHig();
const VIEWABILITY_CONFIG = {
    minimumViewTime: 1500,
    viewAreaCoveragePercentThreshold: 100,
    waitForInteraction: true,
};
const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);
class ShowHistory extends PureComponent {
    constructor(props) {
        super(props);
        this.type = 3;
        this.page = 1;
        this.state = {
            goBack: false
        };
        this.skey = "showhistory_key";
        //this.theme = this.props.theme;
        this.bgColor='#f84a4a';
        this.getHistory();
    }

    componentWillReceiveProps(nextProps) {
        nextProps.status == 'update' ? (nextProps.netInfo && nextProps.netInfo != 'none' ? (this.getData(), this.page = 1) : "") : "";
    }

    componentDidUpdate() {
        this._listRef.getNode().recordInteraction();
    }

    //获取历史记录
    getHistory() {
        DeviceRn().storageGet(this.skey).then(data => {
            if (data != null) {
                let datajson = JSON.parse(data);
                let timerjson = datajson.time;
                this.dataRes = datajson.data;
                this.page = datajson.page;
                this.setState({ data: this.dataRes });
            } else {
                this.props.netInfo != 'none' ? this.getData() : "";
            }
        }).catch(err => {
            this.refs.toast.show('获取数据失败');
        })
    }

    //获取数据
    getData() {
        let payload = {
            type: this.type,
            page: this.page,
            prize: 'true'
        }
        Http().httpPost('plan/consequence', payload).then(data => {
            let resPones = data.data;
            if (this.dataRes != resPones.result) {
                this.page == 1 ? (this.dataRes = resPones.result) : (this.dataRes = this.dataRes.concat(resPones.result));
                this.setState({ data: this.dataRes });
                let paydata = {
                    page: this.page,
                    data: this.dataRes,
                };
                DeviceRn().storageSave(this.skey, JSON.stringify(paydata));
            }
        }).catch(err => {
            this.refs.toast.show('获取数据失败');
        })
    }
    _headerComponent() {
        return (
            <View style={[styles.showHead, { backgroundColor: this.bgColor }]}>
                <Text style={styles.headerTxt}>期号</Text>
                <Text style={styles.headerTxt}>时间</Text>
                <Text style={styles.headerTxt}>号码</Text>
            </View>
        )
    }
    _keyExtractor = (item, index) => index - 1;

    _renderItem = ({ item }) => {
        return (
            <View style={styles.listCont}>
                <Text style={styles.headerTxt}>{item.num}</Text>
                <Text style={[styles.headerTxt, { fontSize: 11 }]}>{item.create_time}</Text>
                <View style={styles.cacleView}>
                    <Text style={[styles.cacleFont, styles.cacle]}>{item.content[0]}</Text>
                    <Text style={styles.cacleFont}> + </Text>
                    <Text style={[styles.cacleFont, styles.cacle]}>{item.content[1]}</Text>
                    <Text style={styles.cacleFont}> + </Text>
                    <Text style={[styles.cacleFont, styles.cacle]}>{item.content[2]}</Text>
                    <Text style={styles.cacleFont}> = </Text>
                    <Text style={[styles.cacleFont, styles.Bcacle]}>{item.count}</Text>
                </View>
            </View>
        );
    }
    _empty = () => {
        return (
            <View style={styles.nodata}>
                <Image style={{ tintColor: this.bgColor }} source={require('../../assets/images/no_data.png')} />
                <Text style={[styles.nodataTxt]}>未加载数据</Text>
            </View>
        )
    }
    _getItemLayout = (data, index) => (
        { length: 72, offset: 72 * index, index }
    )
    _onEndReached = (data) => {
        if (data.distanceFromEnd > 0) {
            this.page++;
            this.page > 6 ? "" : this.getData();
        }
    }
    _scrollPos = new Animated.Value(0);
    _scroll = (e) => {
        this._scrollSinkY;
        let scrollY = e.nativeEvent.contentOffset.y;
        scrollY > 700 ? (this.state.goBack ? "" : this.setState({ goBack: true })) : (this.state.goBack ? this.setState({ goBack: false }) : "");
    }
    _scrollShow() {
        return (
            <View style={[styles.tips, { backgroundColor: this.bgColor }]}>
                <TouchableHighlight onPress={() => this.goTop()} underlayColor={this.bgColor} activeOpacity={0.95} style={[styles.nodata, styles.scroll]} >
                    <Image style={{ tintColor: '#222', width: 40, height: 40 }} source={require('../../assets/images/gotop.png')}></Image>
                </TouchableHighlight>
            </View>
        );
    }
    _scrollSinkX = Animated.event(
        [{ nativeEvent: { contentOffset: { x: this._scrollPos } } }],
        { useNativeDriver: true },
    );
    _scrollSinkY = Animated.event(
        [{ nativeEvent: { contentOffset: { y: this._scrollPos } } }],
        { useNativeDriver: true },
    );
    render() {
        return (
            <View style={styles.cont}>
                <Toast ref="toast" position="center" />
                {this._headerComponent()}
                <View style={styles.showHCont}>
                    <AnimatedFlatList
                        //onRefresh={this._refresh}
                        refreshing={false}
                        data={this.state.data}
                        renderItem={this._renderItem}
                        keyExtractor={this._keyExtractor}
                        getItemLayout={this._getItemLayout}
                        onEndReached={this._onEndReached}
                        ListEmptyComponent={this._empty}
                        onEndReachedThreshold={0.25}
                        initialNumToRender={6}
                        ref={this.captureRef}
                        onScroll={this._scroll}
                        viewabilityConfig={VIEWABILITY_CONFIG}
                        legacyImplementation={false}
                        numColumns={1}
                    />
                </View>
                {this.state.goBack ? this._scrollShow() : null}
            </View>
        );
    }
    captureRef = (ref) => { this._listRef = ref; };
    goTop() {
        this._listRef.getNode().scrollToIndex({ viewPosition: 0, index: 0 });
    }
}
mapStoreState = (store) => ({
    status: store.showHistory.status,
    data: store.showHistory.data
});
export default connect(mapStoreState)(ShowHistory);
const styles = StyleSheet.create({
    cont: {
        flex: 1,
        width: DevWH.sW,
        //alignItems: 'center',
    },
    tips: {
        flex: 0,
        width: 60,
        height: 60,
        flexDirection: 'row',
        justifyContent: 'center',// alignItems: 'center',
        position: 'absolute',
        top: 200,
        right: 20,
        borderRadius: 30,
        opacity: 0.75,
    },
    nodata: {
        flex: 1, justifyContent: 'center', alignItems: 'center'
    },
    scroll: {
        overflow: 'hidden',
        borderRadius: 30,
    },
    nodataTxt: {
        color: '#888',
        marginTop: 15
    },
    showHead: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
        width: DevWH.sW,
        height: 24,
        position: 'absolute',
        top: -10,
    },
    showHCont: {
        flex: 1,
        top: 10,
        marginTop: 5,
        marginBottom: 30,
    },
    cacleView: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    headerTxt: {
        width: DevWH.sW / 4,
        flex: 1,
        textAlign: 'center'
    },
    listCont: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
        width: DevWH.sW,
        height: 72,
        backgroundColor: '#fff',
        borderBottomWidth: 1,
        borderColor: '#f0f0f0',
    },
    contx: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    cacleFont: {
        textAlign: 'center',
        lineHeight: 14,
        width: 14,
        height: 14,
        fontSize: 11,
        overflow: 'hidden',
    },
    cacle: {
        color: '#fff',
        backgroundColor: '#ffc343',
        borderRadius: 7,
        borderWidth: 1,
        borderColor: '#ffc343',
    },
    Bcacle: {
        backgroundColor: '#ff6c3f',
        color: '#fff',
        borderRadius: 8,
        borderWidth: 1,
        borderColor: '#fddfb3',
        width: 16,
        height: 16,
        lineHeight: 16,
    },
});